﻿CREATE PROCEDURE [dbo].[books_validate]
    @bookId int = 0,
    @name nvarchar(256) = null,
    @authorsList nvarchar(1000) = null
AS
DECLARE 
    @authors nvarchar(1000) = null,
    @valid bit = 0
If(@bookId = 0)
    BEGIN
        SELECT 
            @authors = STUFF ( ( SELECT CAST(Authors.AuthorId as nvarchar) +',' FROM Books 
                inner join BooksByAuthor on Books.BookId = BooksByAuthor.BookId 
                inner join Authors on BooksByAuthor.AuthorId = Authors.AuthorId 
                WHERE Books.Title = @name 
                ORDER BY Authors.AuthorId
                FOR XML PATH('')),
                1, 0, '')
    END  
else 
    BEGIN
        SELECT 
            @authors = STUFF ( ( SELECT CAST(Authors.AuthorId as nvarchar) +',' FROM Books 
                inner join BooksByAuthor on Books.BookId = BooksByAuthor.BookId 
                inner join Authors on BooksByAuthor.AuthorId = Authors.AuthorId 
                WHERE Books.Title = @name AND Books.BookId != @bookId
                ORDER BY Authors.AuthorId
                FOR XML PATH('')),
                1, 0, '') 
   END

    If (@authorsList = @authors)
            BEGIN 
                SELECT @valid = 0
            END
        else
            BEGIN
                SELECT @valid =1
            END
   
RETURN @valid
